package com.gwd.task.repository;

import com.gwd.task.entity.CodeSubmitRecordEntity;
import com.gwd.task.model.transfer.RepositoryInterface;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @author zhiyongming
 * @date 2020/12/22 10:15
 */
@Repository
public interface CodeSubmitRecordRepository extends JpaRepository<CodeSubmitRecordEntity, Long> {
    @Modifying
    @Transactional
    @Query(value = "update CodeSubmitRecordEntity u set u.status=1, u.mergerUser=?1, u.mergerTime=?2 where u.csrId in ?3")
    void mergerCode(Long userId, String mergerTime, List<Long> ids);

    @Query(value = "select u from CodeSubmitRecordEntity u where u.projectId=?1 and u.status=0 and u.repId=?2 " +
            "order by u.projectId, u.submitUser, u.submitTime")
    List<CodeSubmitRecordEntity> findByReposAndProject(Long projectId, Long repId);

    @Modifying
    @Transactional
    @Query(value = "UPDATE code_submit ,( " +
            "SELECT m.cr_id, r.project_id, m.type FROM code_repos_relate r, code_repos m WHERE m.cr_id=r.cr_id)alias " +
            "SET code_submit.rep_id=alias.cr_id WHERE code_submit.project_id=alias.project_id AND code_submit.repository=alias.type", nativeQuery = true)
    void matchRepository();

    @Query(value = "select count(u) as num, u.repId as repId from CodeSubmitRecordEntity u where u.status=0 group by u.repId")
    List<RepositoryInterface> countGroupByRep();

    List<CodeSubmitRecordEntity> findByRepIdAndStatus(Long repId, Integer status);

}
